#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import re

from util.gitee_api import Gitee


class Table:
    @staticmethod
    def _table(content):
        return f"<table>{content}</table>"

    @staticmethod
    def _th(content):
        return f"<th>{content}</th>"

    @staticmethod
    def _tr(content):
        return f"<tr>{content}</tr>"

    @staticmethod
    def _td(content):
        return f"<td>{content}</td>"

    @staticmethod
    def _rowspan(num, platform):
        return """<td rowspan="{}">{}</td>""".format(str(num), platform)

    def span_content(self, pr_url, pr_status, commits):
        """
        Splicing comment content
        :param pr_url: pull request url
        :param pr_status: pull request status
        :param commits: commits
        :return: content spliced
        """
        hyperlink_commits = [f"<a href={commit}>{commit}</a>" for commit in commits]
        contents = self._td(pr_url) + self._td(pr_status) + self._td("<br />".join(hyperlink_commits))
        return contents

    def _table_name(self):
        """
        Splicing header
        :return: header
        """
        table_names = ["参考网址", "关联pr", "状态", "补丁链接"]
        table_names = " ".join(map(self._th, table_names))
        return self._tr(table_names)

    @staticmethod
    def _row_span(detail):
        number = 0
        for issues in detail:
            number += len(issues["issue"].get("prs", list()))
        return number

    def table(self, lst):
        """
        Splicing table
        :param lst: cve info
        :return: table
        """
        contents = ""
        for platforms in lst:
            platform_index = 0
            platform = platforms.get("platform")
            if platform and re.search("bugzilla.redhat.com", platform):
                platform = f"https://bugzilla.redhat.com/show_bug.cgi?id={platform.split('/')[-2]}"
            details = platforms.get("details")
            rowspan_content = self._rowspan(self._row_span(details), platform)

            if not details:
                none_tr = self._tr(self._td(platform) + self._td("") * 3)
                contents += none_tr

            for issue_info in details:
                for pr in issue_info["issue"].get("prs", list()):
                    content = self.span_content(
                        pr["url"],
                        pr["status"],
                        pr.get("commits", []),
                    )
                    if platform_index == 0:
                        rowspan_content = rowspan_content + content
                        span_content = self._tr(rowspan_content)
                        platform_index += 1
                    else:
                        span_content = self._tr(content)
                    contents += span_content

        return self._table(self._table_name() + contents)


async def issue_comment(patch_details, number, gitee: Gitee):
    """
    Call gitee's api to add issue comments
    :param patch_details: patch detail
    :param number: issue number
    :param gitee: gitee instance
    :return: None
    """
    table = Table().table(patch_details)
    instruction = "\n" * 2 + "> 说明：抱歉，当前工具暂未找到推荐补丁，请人工查找或者之后评论'/find-patch'尝试再次查找。\n" \
                             "若人工查找到补丁，烦请在此issue下评论 '/report-patch 参考网址 补丁链接1,补丁链接2' 便于我们不断优化工具，不胜感激。\n" \
                             "如 /report-patch https://security-tracker.debian.org/tracker/CVE-2021-3997 https://github.com/systemd/systemd/commit/5b1cf7a9be37e20133c0208005274ce4a5b5c6a1"
    for cve_info in patch_details:
        if cve_info.get("details"):
            instruction = "\n" * 2 + "> 说明：补丁链接仅供初步排查参考，实际可用性请人工再次确认，补丁下载验证可使用" \
                                     "[CVE补丁工具](https://gitee.com/openeuler/cve-manager/blob/master/cve-agency-manager/cve_tracking/README.md)。\n" \
                                     "若补丁不准确，烦请在此issue下评论 '/report-patch 参考网址 补丁链接1,补丁链接2' 反馈正确信息，便于我们不断优化工具，不胜感激。\n" \
                                     "如 /report-patch https://security-tracker.debian.org/tracker/CVE-2021-3997 https://github.com/systemd/systemd/commit/5b1cf7a9be37e20133c0208005274ce4a5b5c6a1"
            break

    body = table + instruction
    await gitee.create_issue_comment(number=number, body=body)
